package com.bc.bcapi.service;

import com.bc.bcapi.dao.T_CountryMapper;
import com.bc.bcapi.dao.T_ProjectMapper;
import com.bc.bcapi.dao.T_Project_cjMapper;
import com.bc.bcapi.dao.T_User_seller_infoMapper;
import com.bc.bcmodel.domain.*;
import com.bc.commoncore.util.*;
import com.bc.commonentity.common.JsonResult;
import com.bc.commonentity.enums.HttpReturnRnums;
import com.bc.commonentity.enums.SeqNameEnum;
import org.apache.cxf.jaxrs.utils.HttpUtils;
import org.apache.xmlbeans.impl.regex.Match;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;
import org.springframework.stereotype.Service;
import org.web3j.crypto.Hash;

import javax.annotation.Resource;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @Name ProjectGenerationService
 * @Description 采集icowatchlist
 * @Author douhaichao
 * @Date 2018/10/6 21:20
 * @Version 1.0
 **/
@Service
public class ProjectGenerationIcoWatchListService {

    @Resource
    T_SequenceService t_sequenceService;
    @Resource
    T_User_seller_infoMapper t_user_seller_infoMapper;
    @Resource
    T_ProjectMapper t_projectMapper;
    @Resource
    T_CountryMapper t_countryMapper;
    @Resource
    T_ProjectMapper t_ProjectMapper;
    @Resource
    T_Project_ceokycService t_project_ceokycService;
    @Resource
    T_Project_contactService t_project_contactService;
    @Resource
    T_Project_cjMapper t_project_cjMapper;

    private static final String domain = "https://icowatchlist.com";

    public JsonResult generationIco() {
        //进行中
        list("/live");
        //即将开始
        list("/upcoming");
        return null;
    }

    private void list(String url) {
        url = domain + url;
        String listHtml = HttpUtil.sendGet(url, "");
        Pattern pattern = Pattern.compile("window.location = '([\\s\\S]+?)'");
        Matcher matcher = pattern.matcher(listHtml);
        while (matcher.find()) {
            try {
                detail(matcher.group(1));
            } catch (Exception e) {
                System.out.print(e.getMessage());
            }
        }
    }

    private void detail(String url) {
        //from_url
        url = domain + "/" + url;
        String html = HttpUtil.sendGet(url, "");

        //ICO Dates
        String icoDate = getIcoDate(html);
        String start_time = icoDate.split(" To ")[0];
        String end_time = icoDate.split(" To ")[1];
        Date start_datetime = DateUtil.getDateByEnglishDate(start_time);
        Date end_datetime = DateUtil.getDateByEnglishDate(end_time);
        //logo
        Pattern pattern_logo = Pattern.compile("<div class=\"col-xs-12 col-md-6\"><img src='(.*?)' class=\"img-responsive\" alt='(.*?)' ></div>");
        Matcher matcher_logo = pattern_logo.matcher(html);
        String logo = matcher_logo.find() ? matcher_logo.group(1) : "";
        //logo下载
        String ico_name = logo.substring(logo.lastIndexOf("/") + 1);
        ico_name = ico_name.substring(0, ico_name.indexOf("."));
        String pid = t_projectMapper.getPidByIcoName(ico_name);
        if (!StringUtils.isEmpty(pid)) {
            System.out.print("已经存在" + pid);
            return;
        }
        downloadLogo(logo);
        //社交开始
        Pattern pattern_shejiao = Pattern.compile("<div class=\"col-xs-6 col-md-3\">Channels</div>([\\s\\S]+?)<div class=\"col-xs-6 col-md-3\">ICO Dates</div>");
        Matcher match_shejiao = pattern_shejiao.matcher(html);
        String shejiaoHtml = match_shejiao.find() ? match_shejiao.group(1) : "";
        pattern_shejiao = Pattern.compile("<a href='(.*?)' target='_blank'>");
        match_shejiao = pattern_shejiao.matcher(shejiaoHtml);
        HashMap<String, String> mapContract = new HashMap<String, String>();
        while (match_shejiao.find()) {
            String value = match_shejiao.group(1);
            String key = getContactKey(value);
            if (StringUtils.isEmpty(key)) {
                continue;
            }
            mapContract.put(key, value);
        }
        //社交结束
        //获取描述
        String description = getDescription(html);
        //Pre-ICO Dates
        String preIcoDate = getPreICODates(html);
        //platform
        String platform = getPlatform(html);
        //Country
        String country = getCountry(html);
        //受限制的国家
        String restricted = getRestricted(html);
        restricted = restricted.replace("\t", "");
        //Total Tokens
        String totalToken = getTotalTokens(html);
        //InitialTokenPrice
        String initialTokenPrice = getInitialTokenPrice(html);
        //Accepted Currencies
        String acceptedCurrencies = getAcceptedCurrencies(html);
        acceptedCurrencies = acceptedCurrencies.replace(" ", "");
        //Whitepaper
        String whitepaper_url = getWhitepaper(html);
        String whitepaper = downloadWhitePaper(whitepaper_url);
        //官网
        String officialSite = getOfficialSite(html);
        //代币名称
        String coinSymbol = getCoinSymbol(html);
        //项目视频
        String videoUrl = getVideo(html);
        //团队信息
        String team = getTeam(html);
        //roadmap
        String roadMap = getRoadMap(html);

        //注册用户B
        String user_id = getUserId(ico_name);
        //创建项目
        pid = setProject(user_id, ico_name, logo, whitepaper,
                videoUrl, restricted, country,
                start_datetime, end_datetime, description,
                totalToken, initialTokenPrice, acceptedCurrencies,
                officialSite, coinSymbol, team,
                mapContract
        );
        setProjectCJ(pid, url, platform, whitepaper_url);
    }

    private void setProjectCJ(String pid, String from_url, String platform, String from_whiltePaper) {
        if (StringUtils.isEmpty(pid)) {
            return;
        }
        T_Project_cjModel t_project_cjModel = new T_Project_cjModel();
        t_project_cjModel.setPid(pid);
        int count = t_project_cjMapper.count(t_project_cjModel);
        if (count > 0) {
            return;
        }
        t_project_cjModel.setFrom_url(from_url);
        t_project_cjModel.setFrom_whitepaper(from_whiltePaper);
        t_project_cjModel.setPlatform(platform);
        t_project_cjMapper.insert(t_project_cjModel);
    }

    /**
     * 添加项目
     */
    private String setProject(
            String user_id, String ico_name, String logo, String white_paper,
            String video_url, String notallow_country, String country,
            Date start_time, Date end_time, String pdesc,
            String totalToken, String tokenPrice, String accepts,
            String officialSite, String ticker, String member_introduction,
            HashMap<String, String> mapContract
    ) {
        String pid = t_projectMapper.getPidByIcoName(ico_name);
        //默认是修改
        boolean isAdd = false;
        if (StringUtils.isEmpty(pid)) {
            isAdd = true;
            pid = t_sequenceService.genSequence(SeqNameEnum.PROJECT_ID);
        }
        T_ProjectModel projectModel = new T_ProjectModel();
        projectModel.setIco_name(ico_name);
        projectModel.setPid(pid);
        projectModel.setStatus(-1);
        projectModel.setImg_project_logo(logo);
        projectModel.setImg_white_paper(white_paper);
        projectModel.setUser_id(user_id);
        projectModel.setPid(pid);
        projectModel.setVideourl(video_url);
        projectModel.setNotallow_country(getCountryId(notallow_country));
        projectModel.setCountry(getCountryId(country));
        projectModel.setStart_time(start_time);
        projectModel.setEnd_time(end_time);
        projectModel.setPdesc(pdesc);
        projectModel.setTotal_tokens(StringUtils.isEmpty(totalToken) ? BigDecimal.ZERO : new BigDecimal(totalToken.replace(",", "")));
        projectModel.setToken_price(StringUtils.isEmpty(totalToken) ? BigDecimal.ZERO : new BigDecimal(tokenPrice.replace(",", "")));
        projectModel.setAccepts(accepts);
        projectModel.setOfficicl_web(officialSite);
        projectModel.setTicker(ticker);
        projectModel.setTid("PT000003002");
        //主要成员介绍
        projectModel.setMember_introduction(member_introduction);

        List<T_Project_contactModel> listContact = getContract(mapContract, pid);
        T_Project_ceokycModel t_project_ceokycModel = new T_Project_ceokycModel();
        t_project_ceokycModel.setPid(pid);
        if (isAdd) {
            //insert
            t_ProjectMapper.insert(projectModel);
            t_project_ceokycService.insert(t_project_ceokycModel);
        } else {
            //update
            projectModel.setModify_time(DateUtil.getToday());
            t_ProjectMapper.update(projectModel);
            t_project_ceokycService.update(t_project_ceokycModel);
            t_project_contactService.delete(pid);
        }
        if (listContact != null && listContact.size() > 0) {
            t_project_contactService.insertBatch(listContact);
        }
        return pid;
    }

    private List<T_Project_contactModel>
    getContract(HashMap<String, String> mapContract, String pid) {
        List<T_Project_contactModel> list = new ArrayList<T_Project_contactModel>();
        if (mapContract.size() <= 0) {
            return list;
        }
        for (String key :
                mapContract.keySet()) {
            String value = mapContract.get(key);
            T_Project_contactModel t_project_contactModel = new T_Project_contactModel();
            t_project_contactModel.setPid(pid);
            if (key.toLowerCase().equals("telegram")) {
                t_project_contactModel.setContact_name("telegram");
                t_project_contactModel.setContact_value(value);
            } else if (key.toLowerCase().equals("github")) {
                t_project_contactModel.setContact_name("github");
                t_project_contactModel.setContact_value(value);
            } else if (key.toLowerCase().equals("biyong")) {
                t_project_contactModel.setContact_name("biyong");
                t_project_contactModel.setContact_value(value);
            } else if (key.toLowerCase().equals("facebook")) {
                t_project_contactModel.setContact_name("facebook");
                t_project_contactModel.setContact_value(value);
            } else if (key.toLowerCase().equals("slack")) {
                t_project_contactModel.setContact_name("slack");
                t_project_contactModel.setContact_value(value);
            } else if (key.toLowerCase().equals("twitter")) {
                t_project_contactModel.setContact_name("twitter");
                t_project_contactModel.setContact_value(value);
            } else {
                continue;
            }
            list.add(t_project_contactModel);
        }
        return list;
    }

    private String getCountryId(String country) {
        try {
            String[] countryArr = country.split(",");
            String country_id = "";
            for (String item :
                    countryArr) {
                if (StringUtils.isEmpty(item)) {
                    continue;
                }
                String cname = item.replace(" ", "");

                int id = t_countryMapper.getCountryId(cname);
                if (id <= 0) {
                    continue;
                }
                if (!StringUtils.isEmpty(country_id)) {
                    country_id = country_id + "|";
                }
                country_id = country_id + id;
            }
            return country_id;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    private String getUserId(String ico_name) {
        //去项目里查询当前ico_name是否存在，存在直接返回项目里的user_id;
//        t_user_seller_infoMapper.getUserIdByIcoName();
//        t_user_seller_infoMapper.getUserIdByName()
        T_User_seller_infoModel t_user_seller_infoModel = new T_User_seller_infoModel();
        t_user_seller_infoModel.setName(ico_name);
        T_User_seller_infoModel model = t_user_seller_infoMapper.findByNamedParam(t_user_seller_infoModel);
        if (model != null) {
            return model.getUser_id();
        }
//        String userId = t_projectMapper.getUserIdByIcoName(ico_name);
//        if (!StringUtils.isEmpty(userId)) {
//            return userId;
//        }
        //注册用户
        String userId = t_sequenceService.genSequence(SeqNameEnum.USER_INFO_SEQ);
//        T_User_seller_infoModel t_user_seller_infoModel = new T_User_seller_infoModel();
        t_user_seller_infoModel.setUser_id(userId);
        t_user_seller_infoModel.setStatus("1");
        t_user_seller_infoModel.setEmail(userId + "@marvel.com");
        t_user_seller_infoModel.setName(ico_name);
        t_user_seller_infoModel.setNick_name(ico_name);
        t_user_seller_infoModel.setRequest_from("icowatchlist.com");
        t_user_seller_infoModel.setPassword(Digest.signMD5("superhero520", Digest.ENCODE));
        t_user_seller_infoMapper.insert(t_user_seller_infoModel);
        return userId;
    }

    //下载白皮书--白皮书可能文件过大，就直接存库里，然后用迅雷批量下载得了。
    private String downloadWhitePaper(String url) {
        String fileName = url.substring(url.lastIndexOf('/') + 1);
        try {
            HttpDownload.downLoadFromUrl(url, fileName, "C:\\Users\\douhaichao\\Desktop\\attr\\whitepaper\\", "");
            return fileName;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "whitepaper/" + fileName;
    }

    //下载LOGO
    private void downloadLogo(String logo) {
        String url = domain + "/" + logo;
        String fileName = url.substring(url.lastIndexOf('/') + 1);
        try {
            HttpDownload.downLoadFromUrl(url, fileName, "C:\\Users\\douhaichao\\Desktop\\attr\\logos\\", "");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private String getDescription(String html) {
        Matcher matcher = Pattern.compile("<p class=\"tabPills\">Description</p>([\\s\\S]+?)<p>&nbsp;</p>")
                .matcher(html);
        String desc = matcher.find() ? StringUtils.delHTMLTag(matcher.group(1)) : "";
        if (!StringUtils.isEmpty(desc)) {
            return desc.trim().replace("(", "（").replace(")", "）").replace("'", "’");
        }
        matcher = Pattern.compile("<p class=\"tabPills\"> Decription </p>([\\s\\S]+?)<p>&nbsp;</p>")
                .matcher(html);
        desc = matcher.find() ? StringUtils.delHTMLTag(matcher.group(1)) : "";
        return desc.trim().replace("(", "（").replace(")", "）").replace("'", "’");
    }

    //roadmap
    private String getRoadMap(String html) {
        Matcher matcher = Pattern.compile("<div class=\"areaBox\" style=\"overflow-y: scroll;overflow-x:hidden; height: 300px;\">([\\s\\S]+?)</div>(?: +)</div>(?: +)</div>(?: +)</div>")
                .matcher(html);
        return matcher.find() ? matcher.group(0) : "";
    }

    //团队信息
    private String getTeam(String html) {
        Matcher matcher = Pattern.compile("<p class=\"tabPills\">Team</p>([\\s\\S]+?)<p class=\"tabPills\">News</p>")
                .matcher(html);
        String teamHtml = matcher.find() ? matcher.group(1) : "";
        if (StringUtils.isEmpty(teamHtml)) {
            return "";
        }
        Matcher matcher_team = Pattern.compile("<img class=\"media-object b-lazy\"(?: +)src=\"https://icowatchlist.com/images/no-photo.jpg\"(?: +)data-src=\"(.*?)\"(?: +)alt=\"(.*?)\" style=\"max-width: 100px; border-radius: 50%;\">")
                .matcher(teamHtml);
        HashMap<String, String> map = new HashMap<String, String>();
        String str = "";
        while (matcher_team.find()) {
            //姓名和职位
            String title = matcher_team.group(2);
            str = str + title + ",";
            if (StringUtils.isEmpty(title)) {
                continue;
            }
            map.put(title.split(" - ")[0], title.split(" - ")[1]);
        }
        return str;
    }

    // 项目视频
    private String getVideo(String html) {
        Matcher matcher =
                Pattern.compile("<div class='embed-container'><iframe src='(.*?)'  frameborder='0' allowfullscreen></iframe></div>")
                        .matcher(html);
        return matcher.find() ? matcher.group(1) : "";
    }

    //    Coin Symbol
    private String getCoinSymbol(String html) {
        Matcher matcher =
                Pattern.compile("<div class=\"col-xs-6 col-md-3\">Coin Symbol</div>(?: +)<div class=\"col-xs-6 col-md-9\">(.*?)</div>")
                        .matcher(html);
        return matcher.find() ? matcher.group(1) : "";
    }

    //    Official Site
    private String getOfficialSite(String html) {
        Matcher matcher =
                Pattern.compile("Whitepaper</a>(?: +)</div>(?: +)<div class=\"col-xs-6 col-md-6\">(?: +)<a href=\"(.*?)\" data-slug='(?:.*?)' data-page='homepage'  target='_blank' rel=\"nofollow\" class=\"btn btn-default btn-lg btn-block btnSuccess oblink\">Official Site</a>")
                        .matcher(html);
        return matcher.find() ? matcher.group(1) : "";
    }

    //    Whitepaper
    private String getWhitepaper(String html) {
        Matcher matcher =
                Pattern.compile("<div class=\"col-xs-6 col-md-6\">(?: +)<a href=\"(.*?)\" data-slug='(?:.*?)' data-page='whitepaper'  rel=\"nofollow\" target='_blank' class=\"btn btn-default btn-lg btn-block btnGrey oblink\">Whitepaper</a>")
                        .matcher(html);
        return matcher.find() ? matcher.group(1) : "";
    }

    //    AcceptedCurrencies
    private String getAcceptedCurrencies(String html) {
        Matcher matcher =
                Pattern.compile("<div class=\"col-xs-6 col-md-3\">Accepted Currencies</div>(?: +)<div class=\"col-xs-6 col-md-9\">(.*?)</div>")
                        .matcher(html);
        return matcher.find() ? matcher.group(1) : "";
    }

    //    Initial Token Price
    private String getInitialTokenPrice(String html) {
        Matcher matcher =
                Pattern.compile("<div class=\"col-xs-6 col-md-3\">Initial Token Price</div>(?: +)<div class=\"col-xs-6 col-md-9\">&#36;(.*?)</div>")
                        .matcher(html);
        return matcher.find() ? matcher.group(1) : "";
    }

    //Total Tokens
    private String getTotalTokens(String html) {
        Matcher matcher =
                Pattern.compile("<div class=\"col-xs-6 col-md-3\">Total Tokens</div>(?: +)<div class=\"col-xs-6 col-md-9\">(.*?)</div>")
                        .matcher(html);
        return matcher.find() ? matcher.group(1) : "";
    }

    //受限制的国家
    private String getRestricted(String html) {
        Matcher matcher =
                Pattern.compile("<div class=\"col-xs-6 col-md-3\">Restricted Countries</div>(?: +)<div class=\"col-xs-6 col-md-9\">(.*?)</div>")
                        .matcher(html);
        return matcher.find() ? matcher.group(1) : "";
    }

    private String getCountry(String html) {
        Matcher matcher =
                Pattern.compile("<div class=\"col-xs-6 col-md-3\">Country</div>(?: +)<div class=\"col-xs-6 col-md-9\"><a href='statistics/geo' target='_blank'>(.*?)</a></div>")
                        .matcher(html);
        return matcher.find() ? matcher.group(1) : "";
    }

    private String getPlatform(String html) {
        Matcher matcher =
                Pattern.compile("<div class=\"col-xs-6 col-md-3\">Platform</div>(?: +)<div class=\"col-xs-6 col-md-9\"><a href='statistics/blockchain' target='_blank'>(.*?)</a></div>")
                        .matcher(html);
        return matcher.find() ? matcher.group(1) : "";
    }

    private String getPreICODates(String html) {
        Matcher matcher =
                Pattern.compile("<div class=\"col-xs-6 col-md-3\">Pre-ICO Dates</div>(?: +)<div class=\"col-xs-6 col-md-9\">(.*?)</div>")
                        .matcher(html);
        return matcher.find() ? matcher.group(1) : "";
    }

    private String getIcoDate(String html) {
        Matcher matcher =
                Pattern.compile("<div class=\"col-xs-6 col-md-3\">ICO Dates</div>(?: +)<div class=\"col-xs-6 col-md-9\">(.*?)</div>")
                        .matcher(html);
        return matcher.find() ? matcher.group(1) : "";
    }

    private String getContactKey(String url) {
        if (StringUtils.isEmpty(url)) {
            return "";
        }
        if (url.contains("twitter")) {
            return "twitter";
        }
        if (url.contains("facebook")) {
            return "facebook";
        }
        if (url.contains("t.me")) {
            return "telegram";
        }
        if (url.contains("youtube")) {
            return "youtube";
        }
        if (url.contains("linkedin")) {
            return "linkedin";
        }
        if (url.contains("reddit")) {
            return "reddit";
        }
        if (url.contains("medium")) {
            return "medium";
        }
        if (url.contains("instagram")) {
            return "instagram";
        }
        if (url.contains("github")) {
            return "github";
        }
        if (url.contains("bitcointalk")) {
            return "bitcointalk";
        }
        return "";
    }


}
